package options;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.TextComponent;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import javax.crypto.CipherInputStream;
import javax.swing.*;
import javax.swing.text.JTextComponent;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import exttable.userdefineextendsclasses.userDefineJFileChooser.UserDefineJFileChooserSelectDirOnly;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import demo.cypher.FileEncrypter;

import exttable.formgenerator.SpringUtilities;
import exttable.threads.ThreadFactory;

import utils.Localisation;

public class SettingsFrame {
	JFrame settingsFrame;
	public static JPanel settingsPanel;
	SpringLayout springLayout;
	JPanel menuPanel;
	JMenuBar jMenuBar;
	JMenuItem menuDataBase;
    JMenu menuGeneral;
	JButton saveButton;
	static JTextField userName;
	static JPasswordField passwordField;
	static JTextField host;
	static JTextField port;
	static boolean isLogIn;
    
    
    static UserDefineJFileChooserSelectDirOnly selectDirOnly
	                                                   ;
	
	public static boolean isLogIn() {
		return isLogIn;
	}
	public static void setLogIn(boolean isLogIn) {
		SettingsFrame.isLogIn = isLogIn;
	}
	public SettingsFrame(){
		createGui();
		
	}
	private void createGui(){
		menuPanel=new JPanel(new GridLayout(1, 1));
		jMenuBar=new JMenuBar();
		menuDataBase=createMenu(Localisation.getMessage("dataBase"));
        menuGeneral=createGeneralMenu("General");
        jMenuBar.add(menuGeneral);
		jMenuBar.add(menuDataBase);
		menuPanel.add(jMenuBar);
		settingsPanel=new JPanel(new SpringLayout());
		settingsPanel.addContainerListener(new ContainerListener() {
			
			@Override
			public void componentRemoved(ContainerEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void componentAdded(ContainerEvent arg0) {
				if(settingsPanel.getComponentCount()<0){
					saveButton.setVisible(false);
				}else{
					saveButton.setVisible(true);
				}
				
			}
		});
//		settingsPanel.setBorder(BorderFactory.createLineBorder(Color.RED,10));
		Dimension dimension=new Dimension((int)Math.round(Toolkit.getDefaultToolkit().getScreenSize().width*0.4),(int)Math.round(Toolkit.getDefaultToolkit().getScreenSize().height*0.3));
		settingsPanel.setPreferredSize(dimension);
		springLayout=new SpringLayout();
		saveButton=new JButton(Localisation.getMessage("error.save"));
		saveButton.setVisible(false);
		saveButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				if(AppSettings.getHashMap().containsKey(settingsPanel.getName())){
					for(Component component:SettingsFrame.settingsPanel.getComponents()){
						for(HashMap<String, String> hashMap:AppSettings.getHashMap().get(settingsPanel.getName())){
							if(hashMap.containsKey(component.getName())){
								hashMap.remove(component.getName());
							}
                            if(component instanceof JTextComponent){
//                                System.out.println("component.getName() : "+component.getName()+"((JTextComponent)component).getText() :"+((JTextComponent)component).getText());
                                hashMap.put(component.getName(), ((JTextComponent)component).getText());
                            }
                            else if(component.getClass().getSimpleName().equals("UserDefineJFileChooserSelectDirOnly")){
                                hashMap.put(component.getName(), ((UserDefineJFileChooserSelectDirOnly)component).getSaveFilesToJTextField().getText());
                            }
                            else if(component instanceof JCheckBox){
                                String booleanValue=((JCheckBox)component).isSelected() ? "true":"false";
                                hashMap.put(component.getName(), booleanValue);
                            }
						}
					
				    }
				}else{
					HashMap<String, String> tempHashMap=new HashMap<String, String>();
					for(Component component:SettingsFrame.settingsPanel.getComponents()){
						if(component instanceof JLabel){
							continue;
						}
                        else if(component instanceof JTextComponent){
//                            System.out.println("component.getName() : "+component.getName()+"((JTextComponent)component).getText() :"+((JTextComponent)component).getText());
                            tempHashMap.put(component.getName(), ((JTextComponent)component).getText());
                        }
                        else if(component.getClass().getSimpleName().equals("UserDefineJFileChooserSelectDirOnly")){
                            tempHashMap.put(component.getName(), ((UserDefineJFileChooserSelectDirOnly)component).getSaveFilesToJTextField().getText());
                        }
				    }
//					AppSettings.put(settingsPanel.getName(), tempHashMap);
					List<HashMap> hList=new ArrayList<HashMap>();
					hList.add(tempHashMap);
					AppSettings.getHashMap().put(settingsPanel.getName(), hList);
				}
				Thread thread=new Thread(ThreadFactory.runSaveConfig());
				thread.start();
				
			}
		});
		settingsFrame=new JFrame(Localisation.getMessage("settings"));
		settingsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		settingsFrame.setSize((int)Math.round(Toolkit.getDefaultToolkit().getScreenSize().width*0.5),(int)Math.round(Toolkit.getDefaultToolkit().getScreenSize().height*0.5));
		settingsFrame.setLayout(springLayout);
		
		
		settingsFrame.add(menuPanel);
		settingsFrame.add(settingsPanel);
		settingsFrame.add(saveButton);
		settingsFrame.setName("settingsFrame");
		settingsFrame.setVisible(true);
		organizeLayout();
		menuPanel.revalidate();
		settingsFrame.validate();
	}
	
	private JMenu createMenu(String name){
		JMenu jMenu=new JMenu(name);
		jMenu.addItemListener(getDataBaseSettingsGui());
		return jMenu;
	}

    private JMenu createGeneralMenu(String name){
        JMenu jMenu=new JMenu(name);
        jMenu.addItemListener(getGeneralSettingsGui());
        return jMenu;
    }
	
	private static void createAuthenticates(){
		settingsPanel.removeAll();
		settingsPanel.setName("dataBaseConnectionSettings");
		JLabel authenticatesLabel=new JLabel(Localisation.getMessage("authenticates"));
		JLabel lineLabel=new JLabel("-----------------------------------------------------------------");
		
		JLabel userNameLabel=new JLabel(Localisation.getMessage("userName"));
		userName=new JTextField(AppSettings.get("dataBaseConnectionSettings", "user","").toString());
		userName.setName("user");
		JLabel userPasswordLabel=new JLabel(Localisation.getMessage("password"));
		passwordField=new JPasswordField(AppSettings.get("dataBaseConnectionSettings", "password","").toString());
		passwordField.setName("password");
		
		JLabel locationLabel=new JLabel(Localisation.getMessage("location"));
		JLabel lineLabel2=new JLabel("-----------------------------------------------------------------");
		JLabel hostLabel=new JLabel(Localisation.getMessage("host"));
		host=new JTextField(AppSettings.get("dataBaseConnectionSettings", "host","").toString());
		host.setName("host");
		
		JLabel portLabel=new JLabel(Localisation.getMessage("port"));
		port=new JTextField(AppSettings.get("dataBaseConnectionSettings", "port","").toString());
		port.setName("port");
		
		settingsPanel.add(authenticatesLabel);
		settingsPanel.add(lineLabel);
		settingsPanel.add(userNameLabel);
		settingsPanel.add(userName);
		settingsPanel.add(userPasswordLabel);
		settingsPanel.add(passwordField);
		
		settingsPanel.add(locationLabel);
		settingsPanel.add(lineLabel2);
		settingsPanel.add(hostLabel);
		settingsPanel.add(host);
		settingsPanel.add(portLabel);
		settingsPanel.add(port);
		int numPairs=settingsPanel.getComponentCount()/2;
		SpringUtilities.makeCompactGrid(settingsPanel,
                numPairs, 2, //rows, cols
                1, 1,        //initX, initY
                100, 1);       //xPad, yPad

        //Set up the content pane.
		settingsPanel.setOpaque(true);  //content panes must be opaque
		if(!isLogIn){
			for(Component component:settingsPanel.getComponents()){
				if(component instanceof JTextComponent){
					((JTextComponent) component).setText("");
				}
			}
		}
		settingsPanel.revalidate();
		settingsPanel.repaint();
	}

    private static void createGeneralSettings(){
        settingsPanel.removeAll();
        settingsPanel.setName("generalSettings");
        JLabel saveFilesToJLabel=new JLabel("save files to");
        selectDirOnly=new UserDefineJFileChooserSelectDirOnly();
        selectDirOnly.setName("saveFileTo");
        selectDirOnly.getSaveFilesToJTextField().setText(AppSettings.get("generalSettings","saveFileTo","").toString());
        settingsPanel.add(saveFilesToJLabel);
        settingsPanel.add(selectDirOnly);

        JCheckBox blockLoginAfterAccessFailuresJCheckBox=new JCheckBox(Localisation.getMessage("lockUserAfterFailedLoginAttempts"));
        blockLoginAfterAccessFailuresJCheckBox.setName("lockUserAfterFailedLoginAttempts");

        JLabel amountAccessFailuresJLabel=new JLabel(Localisation.getMessage("countAccessFailures"));
        final JTextField amountAccessFailuresJTextField=new JTextField(5);
        amountAccessFailuresJTextField.setName("amountAccessFailures");
        amountAccessFailuresJTextField.setText(AppSettings.get("generalSettings", "amountAccessFailures", "").toString());
        amountAccessFailuresJTextField.setEditable(false);

        if(AppSettings.get("generalSettings","lockUserAfterFailedLoginAttempts","").equals("true")){
            blockLoginAfterAccessFailuresJCheckBox.setSelected(true);
            amountAccessFailuresJTextField.setEditable(true);
        }
        blockLoginAfterAccessFailuresJCheckBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if(((JCheckBox) e.getSource()).isSelected()){
                    amountAccessFailuresJTextField.setEditable(true);
                }else{
                    amountAccessFailuresJTextField.setEditable(false);
                }
            }
        });
        settingsPanel.add(blockLoginAfterAccessFailuresJCheckBox);
        settingsPanel.add(amountAccessFailuresJLabel);
        settingsPanel.add(amountAccessFailuresJTextField);
        SpringLayout springLayout=new SpringLayout();
        settingsPanel.setLayout(springLayout);
//        for(Component component:settingsPanel.getComponents()){
//            System.out.println("name : "+component.getName());
//        }
        springLayout.putConstraint(SpringLayout.WEST, saveFilesToJLabel, 0, SpringLayout.WEST, settingsPanel);
        springLayout.putConstraint(SpringLayout.NORTH, saveFilesToJLabel, 10, SpringLayout.NORTH, settingsPanel);

        springLayout.putConstraint(SpringLayout.WEST, selectDirOnly, 20, SpringLayout.EAST, saveFilesToJLabel);
        springLayout.putConstraint(SpringLayout.NORTH, selectDirOnly, 5, SpringLayout.NORTH, settingsPanel);

        springLayout.putConstraint(SpringLayout.WEST, blockLoginAfterAccessFailuresJCheckBox, 0, SpringLayout.WEST, settingsPanel);
        springLayout.putConstraint(SpringLayout.NORTH, blockLoginAfterAccessFailuresJCheckBox, 10, SpringLayout.SOUTH, saveFilesToJLabel);

        springLayout.putConstraint(SpringLayout.WEST, amountAccessFailuresJLabel, 0, SpringLayout.WEST, settingsPanel);
        springLayout.putConstraint(SpringLayout.NORTH, amountAccessFailuresJLabel, 10, SpringLayout.SOUTH, blockLoginAfterAccessFailuresJCheckBox);

        springLayout.putConstraint(SpringLayout.WEST, amountAccessFailuresJTextField, 10, SpringLayout.EAST, amountAccessFailuresJLabel);
        springLayout.putConstraint(SpringLayout.NORTH, amountAccessFailuresJTextField, 0, SpringLayout.NORTH, amountAccessFailuresJLabel);


        settingsPanel.revalidate();
        settingsPanel.repaint();

    }
	
	private void organizeLayout(){
		springLayout.putConstraint(SpringLayout.WEST, menuPanel, 0, SpringLayout.WEST, settingsFrame);
		springLayout.putConstraint(SpringLayout.NORTH, menuPanel, 0, SpringLayout.NORTH, settingsFrame);
		
		springLayout.putConstraint(SpringLayout.WEST, settingsPanel, 0, SpringLayout.WEST, settingsFrame);
		springLayout.putConstraint(SpringLayout.NORTH, settingsPanel, 0, SpringLayout.SOUTH, menuPanel);
		
		springLayout.putConstraint(SpringLayout.WEST, saveButton, 0, SpringLayout.WEST, settingsFrame);
		springLayout.putConstraint(SpringLayout.NORTH, saveButton, 0, SpringLayout.SOUTH, settingsPanel);
		
	}
	
	public static ItemListener getDataBaseSettingsGui() {
        return new ItemListener() {

			@Override
			public void itemStateChanged(ItemEvent e) {
				createAuthenticates();
				
			}
        };
    }

    public static ItemListener getGeneralSettingsGui() {
        return new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                createGeneralSettings();

            }
        };
    }
	
	/**
	 * Возвращает объект Document, который является объектным представлением
	 * XML документа.
	 */
	
	public static void main(String[] args) {
		new SettingsFrame();
		AppSettings.createAppSettings();
	}

}
